#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "tool_mutex.h"
#include "tool_fd.h"
#include "deamon.h"
#include "tool_log.h"

static const char *pidfile = "/tmp/elitah/server.pid";

static int deamon_create(int argc, char **argv, int maxfd)
{
	int i = 0;
	int fd[3] = {0, 0, 0};

	pid_t pc = 0;

	logout("Start to create deamon service...");

	// First fork
	pc = fork();

	if(0 == pc)
	{
		// Here is the parent process
		logoutf("First fork is success...my pid is %d", getpid());

		0 < setsid() ? logout("First setsid() is success...") : logout("First setsid() is failed...");

		// Second fork
		pc = fork();

		if(0 == pc)
		{
			// Second fork was success, Here is the daemon process
			logoutf("Second fork is success...my pid is %d", getpid());

			0 < setsid() ? logout("Second setsid is success...") : logout("Second setsid is failed...");

			chdir("/");
			umask(0);

			for(i = 0; i < maxfd; i++)
			{
				close(i);
			}
			fd[0] = open("/dev/null", O_RDWR);
			fd[1] = dup(0);
			fd[2] = dup(0);

			if(0 != fd[0] || 1 != fd[1] || 2 != fd[2])
			{
				logout("Close all file descriptors failed...");
				return EXIT_FAILURE;
			}

			if(EXIT_SUCCESS != create_mutex(pidfile))
			{
				logout("Can not create lock file...");
				return EXIT_FAILURE;
			}

			logout("Init Success, start the deamon main...");

			// start the daemon process
			return deamon_main(argc, argv);
		}
		else if (0 < pc)
		{
			// Second fork was success, Here is the parent process
			return EXIT_SUCCESS;
		}
		else
		{
			// Second fork was failed, Here is the parent process
			logout("Second fork is failed...");
			return EXIT_FAILURE;
		}
	}
	else if (0 < pc)
	{
		// First fork was success, Here is the grandparent process
		return EXIT_SUCCESS;
	}
	else
	{
		// Second fork was failed, Here is the grandparent process
		logout("First fork is failed...");
		return EXIT_FAILURE;
	}
}

int main(int argc, char **argv)
{
	int maxfd = get_maxfd();

	if(EXIT_SUCCESS != init_logdir())
	{
		printf("Failure, unable to create the log folder, permission denied!\n");
		return EXIT_FAILURE;
	}

	init_mutex(pidfile);

	logoutf("Service is starting now...mypid is %d", getpid());

	return deamon_create(argc, argv, maxfd);
}
